import Vue from 'vue'
import VueRouter from 'vue-router'
import {getUserPermissions} from "@/api/user";
import store from "@/store/index";
import {listToTree} from "@/utils/treeUtil";

Vue.use(VueRouter)

const routes = [
    {
        path: '/',
        redirect: "/login"
    },
    {
        path: '/login',
        name: 'login',
        component: () => import('../views/commons/LoginView.vue')
    },
    {
        path: '/index',
        name: 'index',
        redirect: "/home",
        component: () => import('../views/commons/IndexView'),
        children: []
    }
]

const router = new VueRouter({
    routes
})


//路由守卫    to  需要跳转的路径  to.path    from  从哪个路径来     next  是否放行
router.beforeEach(async (to, from, next) => {
    //1. 用户没有登录不能直接访问  /index
    //2.用户已经登录  访问 /login   -> /index
    let path = to.path;
    let token = localStorage.getItem("token");


    if (token && path == "/login") {
        next("/index")
    }

    if (!token && path != "/login") {
        next("/login")
    }

    // 获取用户的权限信息
    if (token) {
        if (store.state.menuData.length == 0) {
            let {data} =  await getUserPermissions()
            let treeMenu = [
                {title:'首页',icon:'el-icon-menu',path:'/home'},
                ...listToTree(data)
            ]
            // 将菜单数据 存入  vuex  state
            store.commit("changMenuData",treeMenu)

            // 动态添加路由
            let  routerMenu = data.filter(r=>r.isMenu==1)
                .map(r=>{
                    return{
                        path: r.path,
                        component: () => import('@/views/'+r.model+'/'+r.component) // () => import('@/views/system/UserView')
                    }
                })

            let newRouter = [
                {
                    path: '/home',
                    name: 'home',
                    component: () => import('@/views/commons/HomeView')
                },
                ...routerMenu,
                {
                    path: '/**',
                    name: 'page404',
                    component: () => import('@/views/commons/Page404View')
                }
            ]

            newRouter.forEach(nrt=>{
                router.addRoute("index",nrt)
            })
            next(to.path)
        }
    }
    next()  // 放行
})

export default router
